package com.hmdp.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.myconst.KeyConst;
import com.hmdp.utils.UserHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.hmdp.myconst.KeyConst.LOGIN_USER_TOKEN;

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //1.先获取对应的token
        String token = request.getHeader("authorization");
        //2.判断token的存在性
        if(StrUtil.isBlank(token)){
            return true;
        }
        //3.比对token
        String userStr = redisTemplate.opsForValue().get(LOGIN_USER_TOKEN + token);
        if(StrUtil.isBlank(userStr)){
            return true;
        }
        //4.保存在ThreadLocal
        //4.1转化成类-->uto
        UserDTO userDTO = JSONUtil.toBean(userStr, UserDTO.class);
        //4.2存储
        UserHolder.saveUser(userDTO);
        //5.刷新token
        redisTemplate.expire(LOGIN_USER_TOKEN + token,10, TimeUnit.MINUTES);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if(ObjectUtil.isNotNull(UserHolder.getUser())){
            UserHolder.removeUser();
        }
    }
}
